Description:
DUCOCRV detects incorrect type casts caused by incorrect usage of "type codes".
This error may occur when the type of an object in a hierarchy of classes
is determined by examining the value returned by the qualificator method. A warning
message is shown when the value returned by a qualificator method is compared
with a constant that is returned by an implementation of the qualificator method
in type A and then inside the same conditional branch the object is
casted to type B that is not the same type as A
and is not a base type of A.
Incorrect:
abstract class Expression {
public const int Unary = 0;
public const int Binary = 1;
public abstract int getKind();
}
class UnaryExpression : Expression {
public override int getKind() {
return Unary;
}
public Expression getOperand() { ... }
}
class BinaryExpression : Expression {
public override int getKind() {
return Binary;
}
public Expression getLeftOperand() { ... }
public Expression getRightOperand() { ... }
}
void eval(Expression expr) {
if (expr.getKind() == Expression.Unary) {
eval(((BinaryExpression) expr).getLeftOperand());
...
}
Correct:
void eval(Expression expr) {
if (expr.getKind() == Expression.Unary) {
eval(((UnaryExpression) expr).getOperand());
...
}